<template>
  <div class="subjectsAdd">
    <!-- 头部 -->
    <headerTop title="创建考试"></headerTop>

    <!-- 基本信息 -->
    <div class="subjects">
      <div class="message">
        <div class="span">1</div>
        <div>基本信息</div>
      </div>
      <div class="input_one">
        <el-form :model="data" label-width="220px">
          <el-form-item label="考试名称：">
            <el-input v-model="params.title" class="elinput_one" />
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 内容设置 -->
    <div style="margin-top: 30px" class="subjects">
      <div class="message">
        <div class="span">2</div>
        <div>内容设置</div>
      </div>
      <div class="content">
        <el-form :model="data" label-width="220px">
          <el-form-item label="试卷内容：">
            <div class="content_nav">
              <div class="content_top">
                <h3>试题列表</h3>
                <div class="content_right">
                  <span>总分：{{ Total }}</span>
                  <span class="span_two">已添加{{ params.questions.length }}题</span>
                  <el-button style="font-size: 13px" @click="dell">清空</el-button>
                </div>
              </div>

              <!-- 显示每题题数和分数 -->
              <div class="testContent" v-show="params.questions.length > 0">
                <div class="topic" v-if="ifChoice == true">
                  <span style="margin-left: 10px">单选题{{ numChoice }}道</span>
                  <p style="margin-left: 10px" class="each">
                    每题<el-input v-model="scoreContent" class="num" />分
                  </p>
                </div>
                <div class="topic" v-if="ifMuch">
                  <span style="margin-left: 10px">多选题{{ numMuch }}道</span>
                  <p style="margin-left: 10px" class="each">
                    每题<el-input v-model="scoreMuch" class="num" />分
                  </p>
                </div>
                <div class="topic" v-if="ifJudge">
                  <span style="margin-left: 10px">判断题{{ numJudge }}道</span>
                  <p style="margin-left: 10px" class="each">
                    每题<el-input v-model="scoreJudge" class="num" />分
                  </p>
                </div>
                <div class="topic" v-if="ifTopic">
                  <span style="margin-left: 10px">填空题{{ numTopic }}道</span>
                  <p style="margin-left: 10px" class="each">
                    每题<el-input v-model="scoreTopic" class="num" />分
                  </p>
                </div>
                <div class="topic" v-if="ifProblem">
                  <span style="margin-left: 10px">问答题{{ numProblem }}道</span>
                  <p style="margin-left: 10px" class="each">
                    每题<el-input v-model="scoreProblem" class="num" />分
                  </p>
                </div>
              </div>

              <!-- 试题添加 -->
              <div class="gotContentBox" v-show="params.questions.length > 0">
                <div class="gotContent" v-for="(item, index) in params.questions"
                  :key="item.id">
                  <div class="gotTop">
                    <div class="gotLeft">
                      <span>{{ index + 1 + "." + item.type }}</span>
                      <span style="padding-left: 10px">分值</span>
                      <el-form-item>
                        <el-input v-model="item.scores" class="gotLeft_input" />
                      </el-form-item>
                    </div>
                    <div class="gotRight">
                      <span>
                        <el-icon><EditPen @click="amend(item, index)"/></el-icon>
                      </span>
                      <span style="padding: 0px 10px">
                        <el-icon><Delete @click="del(index, item.type)"/></el-icon>
                      </span>
                    </div>
                  </div>
                  
                  <!-- 单选题 -->
                  <div
                    v-show="item.type === '单选题'"
                    :class="
                      item.answer === items.answerno ? 'options' : 'optio'
                    "
                    v-for="items in item.answers"
                    :key="items.id"
                  >
                    <el-radio :label="items.answerno + '：'"></el-radio>
                    <span>{{ items.content }}</span>
                  </div>
                  <!-- 多选题 -->
                  <div
                    v-show="item.type === '多选题'"
                    :class="
                      item.answer.indexOf(items.answerno) != -1
                        ? 'options'
                        : 'optio'
                    "
                    v-for="items in item.answers"
                    :key="items.id"
                  >
                    <el-checkbox :label="items.answerno + '：'"></el-checkbox>
                    <span>{{ items.content }}</span>
                  </div>
                  <!-- 填空题判断题 -->
                  <div
                    v-if="item.type === '填空题' || item.type === '判断题'"
                    class="judge"
                  >
                    <span>正确答案</span>
                    <span style="margin-left: 20px">{{ item.answer }}</span>
                  </div>
                  <!-- 填空题问答题 -->
                  <div
                    v-if="item.type === '填空题' || item.type === '问答题'"
                    class="jud"
                  >
                    <span>答案解析：</span>
                    <span>{{ item.explains }}</span>
                  </div>
                </div>
              </div>

              <!-- 添加试题的按钮 -->
              <div class="buttons">
                <el-button @click="addTitle">添加题目</el-button>
                <el-button @click="batchImport">批量导入</el-button>
                <el-button @click="openList">从题库中导入</el-button>
              </div>
            </div>

            <!-- 题库 -->
          </el-form-item>
          <el-form-item label="试题存入题库：" prop="content">
            <el-select v-model="region" placeholder="请选择题库">
              <el-option
                v-for="item in regions"
                :label="item.title"
                :value="item.id"
                :key="item.id"
              />
            </el-select>
            <el-button style="font-size: 13px; margin-left: 13px"
              @click="questionbank">+ 创建试题库</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <!-- 教师模范 -->
      <div class="subjects">
        <div class="message">
          <div class="span">3</div>
          <div>教师模范</div>
        </div>
        <div class="viTeacher">
          <el-form class="demo-form-inline">
            <el-form-item label="可见老师：">
              <el-badge :value="limits.length" class="item" type="primary">
                <el-button style="font-size: 13px; width: 72px"
                @click="teacher">+ 选择</el-button
                >
              </el-badge>
            </el-form-item>
          </el-form>
        </div>
        <div class="but">
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>

        <!-- 可见老师的弹出框 -->
        <transferBase v-show="dialogStore.show && dialogStore.type === 'text'" @addSelected="addSelected"></transferBase>

        <!-- 题库添加的弹框 -->
        <AddBase v-show="dialogStore.show && dialogStore.type !== 'text'"></AddBase>

        <!-- 添加题目抽屉-->
        <Drawer :isTitle="isTitle" v-if="isTitle == true" :index="index" @isClose="isClose" @addSave="addSave" :title="titles"></Drawer>

        <!-- 引入题库列表组件 -->
        <bankList :questionBool="questionBool" @queshandleClose="queshandleClose" @testlistConfirm="testlistConfirm"
        @quesConfirm="quesConfirm"></bankList>

         <!-- 批量导入 -->
        <Import @imports="imports" :isImport="isImport" @isImports="isImports"></Import>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive,toRefs,watchEffect,watch } from 'vue';
import headerTop from '../../components/header/headerTop.vue';
import {databaseList,subjectsAdd,subjectsGet} from '../../api/subjects';
import { useDialogStore } from '../../store/dialog';
import transferBase from '../../components/transferBase/transferBase.vue'
import { useRoute,useRouter } from 'vue-router';
import AddBase from '../../components/textAdmin/AddBase.vue'
import Drawer from '../../components/textAdmin/Drawer.vue'
import { EditPen, Delete } from '@element-plus/icons-vue';
import bankList from '../../components/textAdmin/bankList.vue'
import { ElMessage } from "element-plus";
import Import from '../../components/textAdmin/Import.vue'

const route = useRoute();
console.log(route.query);
const data: any = reactive({
  params: {
    id: 0,//当前考试的id
    title: "",//标题
    info: "",//说明
    admin: "ldq",//登录的用户名
    begintime: "",//开始时间
    endtime: "",//结束时间
    limittime: "",// 限制时长
    scores: 100,//总分
    state:null,
    pastscores: 60, // 通过分数
    qorder: 0,//防作弊试题打乱
    aorder: 0,//防作弊试题打乱-单选多选判断题
    answershow: 1,//交卷后的显示别: 1 ~5
    isshow:1,//题库是否被他人使用（全部可见1，全部不可见2，部分可见3）
    databaseid: 20,//当前考试的基础id
    limits: [],    // 可见老师
    markteachers: [],// 阅卷老师
    students: [],// 考生范围
    questions: [],// 试题添加数据
  },
  // 实体存入题库
  region: [],
  regions: [],
  // 分值
  score: "",
  titles:'',
  // 防作弊
  checked1: "",
  checked2: true,
  questionBool:false,
  // 弹出添加试卷
  isTitle: false,
  Total: 0,//总分
  scoreContent: "",
  scoreMuch: "",
  scoreJudge: "",
  scoreTopic: "",
  scoreProblem: "",
  ifChoice: false,//单选题
  ifMuch: false,//多选题
  ifJudge: false,//判断题
  ifTopic: false,//填空题
  ifProblem: false,//问答题
  isShow: false,
  nums: 0,
  // 考试ID
  test: 0,
  numChoice: 0,//单选题的数量
  numMuch: 0,//多选题的数量
  numTopic: 0,//判断题的数量
  numProblem: 0,//填空题的数量
  numJudge: 0,//问答题的数量
  Tips: "",
  index: -1,
  isImport:false
});
const {
  numChoice,
  numMuch,
  numTopic,
  numProblem,
  numJudge,
  ifChoice,
  ifMuch,
  ifJudge,
  ifTopic,
  ifProblem,
  scoreContent,
  scoreMuch,
  scoreJudge,
  scoreTopic,
  scoreProblem,
  Total,
  params,
  region,
  regions,
  isTitle,
  index,
  titles,
  questionBool,
  isImport
}: any = toRefs(data);
const router = useRouter();
const dialogStore = useDialogStore()
const { show, title,type } = toRefs(dialogStore)
const textSubject = ref(false);
const limits = ref([])

// 获取题库列表接口
const baseList = async () => {
  const res = await databaseList({});
  regions.value = res.data.list;
};
baseList();

// 可见老师
const teacher = ()=>{
  dialogStore.$patch(state=>{
    state.show=true
    state.type='text'
    state.title='可见老师'
  })
}

// 点击确定按钮关闭弹窗
const addSelected = ()=>{
  dialogStore.$patch(state=>{
    state.show=false
  })
}

// 添加题目
const addTitle = ()=>{
  titles.value='添加'
  isTitle.value = true;
}

// 添加试卷
const addSave = (e:boolean,b:string)=>{
  console.log(b);
  params.value.questions.push(b); //子组件传过来的数据
  isTitle.value = e;
}

// 点击试卷确定添加题目
const testlistConfirm = (val:any)=>{
  console.log(val);
  let infos = val
  infos.map((item: any) => params.value.questions.push(item));
  questionBool.value=false
}

// 打开题库弹框
const openList = ()=>{
  questionBool.value=true
}

// 关闭题库列表
const quesConfirm = (val:boolean)=>{
  questionBool.value=val
}

// 关闭题库列表弹框
const queshandleClose = (val:boolean)=>{
  questionBool.value=val
}

// 关闭抽屉的方法
const isClose = (e: any) => {
  isTitle.value = e;
};

// watch监听
watchEffect(() => {
  let Choice = 0;
  let Much = 0;
  let Topic = 0;
  let Problem = 0;
  let Judge = 0;
  params.value.questions.forEach((item: any) => {
    if (item.type === "单选题") {
      data.ifChoice = true;
      Choice += 1;
    } else if (item.type === "多选题") {
      ifMuch.value = true;
      Much += 1;
      // nums.value+1
    } else if (item.type === "填空题") {
      ifTopic.value = true;
      Topic += 1;
      // nums.value+=1
    } else if (item.type === "问答题") {
      ifProblem.value = true;
      Problem += 1;
      // nums.value+=1
    } else if (item.type === "判断题") {
      ifJudge.value = true;
      Judge += 1;
    }
  });
  numChoice.value = Choice;
  numMuch.value = Much;
  numTopic.value = Topic;
  numProblem.value = Problem;
  numJudge.value = Judge;
});

// 修改
const amend = (row: any, index: number)=>{
  data.obj = JSON.parse(JSON.stringify(row))
  titles.value='修改'
  isTitle.value = true;
  data.index = index;
}

// 删除
const del = (index: number, type: String) => {
  if (type === "单选题") {
    if (numChoice.value > 1) {
      numChoice.value -= 1;
    }
    data.ifChoice = false;
    params.value.questions.splice(index, 1);
  }
  if (type === "多选题") {
    data.ifMuch = false;
    params.value.questions.splice(index, 1);
  }
  if (type === "判断题") {
    data.ifJudge = false;
    params.value.questions.splice(index, 1);
  }
  if (type === "填空题") {
    data.ifTopic = false;
    params.value.questions.splice(index, 1);
  }
  if (type === "问答题") {
    data.ifProblem = false;
    params.value.questions.splice(index, 1);
  }
};
// 清空
const dell = () => {
  params.value.questions = [];
  ifChoice.value = false,
  ifMuch.value = false,
  ifJudge.value = false,
  ifTopic.value = false,
  ifProblem.value = false
};
let isshow = ref(true)

// 题库添加
const questionbank = ()=>{
  dialogStore.$patch(state=>{
    state.show=isshow.value
    state.title='题库添加'
  })
}

// 批量导入
const batchImport=()=>{
  isImport.value = true
}
const imports = (e:any)=>{
  params.value.questions = e
}
const isImports=(e:any)=>{
  isImport.value=e
}

// 监听
watchEffect(() => {
  var num = 0;
  params.value.questions.map((item: any, index: number) => {
    num = Number(item.scores) + Number(num);
  });
  Total.value = num;
});
watch([scoreContent], () => {
  params.value.questions.map((item: any) => {
    if (item.type === "单选题") {
      item.scores = scoreContent.value;
    }
  });
});
watch([scoreMuch], () => {
  params.value.questions.map((item: any) => {
    if (item.type === "多选题") {
      item.scores = scoreMuch.value;
    }
  });
});
watch([scoreJudge], () => {
  params.value.questions.map((item: any) => {
    if (item.type === "判断题") {
      item.scores = scoreJudge.value;
    }
  });
});
watch([scoreTopic], () => {
  params.value.questions.map((item: any) => {
    if (item.type === "填空题") {
      item.scores = scoreTopic.value;
    }
  });
});
watch([scoreProblem], () => {
  params.value.questions.map((item: any) => {
    if (item.type === "问答题") {
      item.scores = scoreProblem.value;
    }
  });
});

// 数据回显
const Echo = async () => {
  const res: any = await subjectsGet({id:route.query.id});
  if (res.errCode === 10000) {
    data.params = res.data;
  } 
};
if (Number(route.query.id) != 1) {
  Echo();
}

// 提交
const submit = async()=>{
  if (!params.value.title) {
    ElMessage.error("请填写试卷名称");
    return;
  } else if (params.value.questions.length === 0) {
    ElMessage.error("请添加题目");
    return;
  } 
    Total.value = params.scores;
    console.log(params.value);
    // 添加
    params.value.id=route.query.id
    if(!params.value.id){
      const res: any = await subjectsAdd(params.value);
    if (res.errCode === 10000) {
      ElMessage.success("添加成功！");
      router.push("/subjects");
    } else {
      ElMessage.error(res.errMsg);
    }
    }
    else if(params.value.id===route.query.id){
      const res: any = await subjectsAdd(params.value);
    if (res.errCode === 10000) {
      ElMessage.success("修改成功！");
      router.push("/subjects");
    } else {
      ElMessage.error(res.errMsg);
    }
    }
}

// 取消
const cancel = ()=>{
  router.push('/subjects');
}
</script>

<style lang="less" scoped>
.subjectsAdd {
  width: 100%;
  height: 100%;
  .subjects {
    width: 100%;
    .message {
      width: 99%;
      height: 56px;
      display: flex;
      background-color: #f9faff;
      line-height: 56px;
      margin-left: 10px;
      .span {
        font-size: 35px;
        color: #c7e5ff;
        margin: 0 20px;
      }
    }
    .input_one {
      margin-top: 20px;
      .elinput_one {
        width: 378px;
      }
    }
  }
  .content {
    margin-top: 20px;
    .content_nav {
      width: 1025px;
      border: 1px solid #dcdfe6;
      .content_top {
        padding: 10px 15px;
        border-bottom: 1px solid #dcdfe6;
        display: flex;
        justify-content: space-between;
      }
      .content_right {
        color: #90909e;
        .span_two {
          padding: 0 40px;
        }
      }
    }
  }
  .testContent {
    width: 120px;
    position: absolute;
    left: -130px;
    font-size: 13px;
    color: #848484;
    .topic {
      width: 100%;
      border: solid 1px #ececec;
      padding: 7px 0;
    }
    .each {
      display: flex;
      margin-top: 10px;
      align-items: center;
    }
    :deep(.num) {
      width: 45px;
    }
  }
  .buttons {
    padding: 10px 15px;
    border-top: 2px solid #dcdfe6;
    .el-button {
      font-size: 12px;
    }
  }
  .gotContentBox {
    overflow-y: scroll;
    max-height: 70vh;
    .gotContent {
      padding: 20px 15px;
      overflow-y: auto;
      .gotTop {
        display: flex;
        color: #6a6a6a;
        justify-content: space-between;
        .gotLeft {
          display: flex;
          .gotLeft_input {
            width: 80px;
            margin-left: 10px;
          }
        }
        .gotRight {
          font-size: 20px;
          color: #299aff;
        }
      }
    }
  }
  .viTeacher {
    margin-left: 140px;
  }
  .but {
    margin-left: 222px;
    margin-top: 40px;
  }
  .options{
    background-color: #eefaf6;
  }
  .judge{
    background-color: #eefaf6;
    color: #5acda6;
    padding: 8px;
  }
  .jud{
    background-color: #f5faff;
    color: #9dadbc;
    padding: 8px;
    margin-top: 10px;
  }
}
</style>
